import { Feed } from "feed";
import { getPosts } from "@src/services/posts";

/**
 * 生成 RSS Feed
 * @returns Feed 实例
 */
export const generateRSSFeed = async () => {
  // 创建 Feed 实例
  const feed = new Feed({
    title: "BLOG Code",
    description: "This is my personal blog site",
    id: "http://example.com/",
    link: "http://example.com/",
    language: "zh", // optional, used only in RSS 2.0, possible values: http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
    image: "http://example.com/image.png",
    favicon: "http://example.com/favicon.ico",
    copyright: "All rights reserved 2025, yangsir",
    updated: new Date(), // optional, default = today
    generator: "awesome", // optional, default = 'Feed for Node.js'
    feedLinks: {
      json: "http://example.com/rss/json",
      atom: "http://example.com/rss/atom",
      rss: "http://example.com/rss"
    },
    author: {
      name: "yangsir",
      email: "yangsir@example.com",
      link: "https://example.com/yangsir"
    }
  });

  // 获取所有文章
  const posts = await getPosts();

  // 将文章添加到 feed 中
  if (Array.isArray(posts)) {
    posts.forEach((post) => {
      feed.addItem({
        title: post.title || "无标题",
        id: `http://example.com/posts/${post.id}`,
        link: `http://example.com/posts/${post.id}`,
        description: post.content || "",
        content: post.content || "",
        author: [
          {
            name: "yangsir",
            email: "yangsir@example.com",
            link: "https://example.com/yangsir"
          }
        ],
        date: post.updated_at ? new Date(post.updated_at) : new Date(),
        image: post.thumbimage ? `http://example.com${post.thumbimage}` : undefined
      });
    });
  }

  return feed;
};

/**
 * 生成 RSS 2.0 格式
 */
export const generateRSS2 = async () => {
  const feed = await generateRSSFeed();
  return feed.rss2();
};

/**
 * 生成 Atom 1.0 格式
 */
export const generateAtom = async () => {
  const feed = await generateRSSFeed();
  return feed.atom1();
};

/**
 * 生成 JSON Feed 格式
 */
export const generateJSON = async () => {
  const feed = await generateRSSFeed();
  return feed.json1();
};
